package com.dhecp.common.utils.pdf;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import org.xhtmlrenderer.pdf.ITextRenderer;

import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.BaseFont;

import freemarker.template.Configuration;
import freemarker.template.Template;

public class FreeMarkerPdfUtil {

	public static void main(String[] args) throws Exception {
		//		这里是选择某个模板
		String templateName = "aa.ftl";
		Map<String, Object> paramMap = new HashMap<String, Object>();
		//这里是给具体的某些字段赋值
		paramMap.put("ZJHKZH", "271003********279975");
		//调用具体的实现方法
		String templatePath = "D:\\data\\test\\";
		String desDir = "D:\\data\\test\\";
		String htmlName = "temp.html";
		String desPdfName = "PD886221223001.pdf";
		String fontDir = "D:\\data\\test\\";
		createPdf(templatePath, templateName, desDir, htmlName, desPdfName, fontDir, paramMap);
	}
	
	/**
	 * 
=======

	/**
	 *
>>>>>>> 85263f750780d16b5ec1fd39627d014858df05f6
	 * @param templatePath
	 * @param templateName 模板名称，如：aa.ftl
	 * @param desDir 目标路径，如：D:/data/test/
	 * @param tempHtmlName 临时根据FTL模板生成的HTML文件命名，如:PD886221223001.html
	 * @param desPdfName 目标PDF文件名，如:PD886221223001.pdf
	 * @param fontDir 字体文件目录，如:D:/data/test/
	 * @param paramMap
	 */
	public static void createPdf(String templatePath, String templateName, String desDir, String tempHtmlName, String desPdfName, String fontDir, Map<String, Object> paramMap) {
		// 获取本地模板存储路径、合同文件存储路径
//		String templatePath = TEMPLATE;
		// 组装html和pdf合同的全路径URL
		String localHtmlUrl = desDir + tempHtmlName;
		// 判断本地路径是否存在如果不存在则创建
		File localFile = new File(desDir);
		if (!localFile.exists()) {
			localFile.mkdirs();
		}
		String localPdfUrl = desDir + desPdfName;
		try {
			htmHandler(templatePath, templateName, localHtmlUrl, paramMap);// 生成html合同
			pdfHandler(localHtmlUrl, localPdfUrl, fontDir);
		} catch (Exception e) {
			e.printStackTrace();
		}// 根据html合同生成pdf合同
//		deleteFile(localHtmlUrl);// 删除html格式合同
		
		System.out.println("PDF生成成功");
	}

	private static void htmHandler(String templatePath, String templateName, String htmUrl, Map<String, Object> paramMap) throws Exception {
		Configuration cfg = new Configuration();
		cfg.setDefaultEncoding("UTF-8");
		cfg.setDirectoryForTemplateLoading(new File(templatePath));
		
		Template template = cfg.getTemplate(templateName);
		
		File outHtmFile = new File(htmUrl);
		
		Writer out = new BufferedWriter(new OutputStreamWriter(
		new FileOutputStream(outHtmFile)));
		template.process(paramMap, out);
		
		out.close();
	}
	
	/**
	 * 
=======

		Template template = cfg.getTemplate(templateName);

		File outHtmFile = new File(htmUrl);

		Writer out = new BufferedWriter(new OutputStreamWriter(
				new FileOutputStream(outHtmFile)));
		template.process(paramMap, out);

		out.close();
	}

	/**
	 *
	 * @param htmUrl
	 * @param pdfUrl
	 * @param fontDir 字体文件目录，如：D:/data/test/
	 * @throws DocumentException
	 * @throws IOException
	 */
	private static void pdfHandler(String htmUrl, String pdfUrl, String fontDir) throws DocumentException, IOException {
        File htmFile = new File(htmUrl);
        File pdfFile = new File(pdfUrl);

        String url = htmFile.toURI().toURL().toString();
        
        System.setProperty("javax.xml.transform.TransformerFactory", "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl");
        OutputStream os = new FileOutputStream(pdfFile);

        ITextRenderer renderer = new ITextRenderer();
        renderer.setDocument(url);

        org.xhtmlrenderer.pdf.ITextFontResolver fontResolver = renderer
                .getFontResolver();
        // 解决中文支持问题
//		fontResolver.addFont(TEMPLATE+"simsun.ttc",
//				BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

		try {
			fontResolver.addFont(fontDir + "simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
		} catch (com.itextpdf.text.DocumentException e) {
			e.printStackTrace();
		}

        renderer.layout();
        try {
            renderer.createPDF(os);
        } catch (com.itextpdf.text.DocumentException e) {
            e.printStackTrace();
        }
        os.close();
    }
}
